package com.example.administrator.text;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.ClipImageLayout;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.UploadDialog;


/**
 * 裁剪头像图片的Activity
 *
 */
public class ClipImageActivity extends BaseActivity{
	private ClipImageLayout mClipImageLayout = null;
	private UploadDialog mUploadDialog;
	private String mPath,mToken,mId;
	private String path;
	private String IMAGE_FILE_NAME = "clip_temp.jpg";    //选择头像 相机 图片保存的名字
	private String RESULT_PATH = "result_path";
	private String PASS_PATH = "pass_path";
	private File mFile;

	@Override protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clip_image);
		LinearLayout relativeLayout = (LinearLayout)findViewById(R.id.relati_clip);
		HomeUtil.getHemeUtilNew().getStatusBar(this,relativeLayout);
		init();
		// 有的系统返回的图片是旋转了，有的没有旋转，所以处理
		int degreee = readBitmapDegree(mPath);
		Bitmap bitmap = createBitmap(mPath);
		if (bitmap != null) {
			if (degreee == 0) {
				mClipImageLayout.setImageBitmap(bitmap);
			} else {
				mClipImageLayout.setImageBitmap(rotateBitmap(degreee, bitmap));
			}
		} else {
			finish();
		}
	}

	View.OnClickListener l = new View.OnClickListener() {
		@Override public void onClick(View v) {
			switch (v.getId()){
				case R.id.tv_use:
					mUploadDialog = new UploadDialog(ClipImageActivity.this,"上传中");
					mUploadDialog.show();
					mToken = (String) SharedPreferencesUtils.getParam(ClipImageActivity.this, HomeUtil.mTokenDB,"");
					mId = (String) SharedPreferencesUtils.getParam(ClipImageActivity.this, HomeUtil.mUseridDB,"");
					HomeUtil.mHUExecutorService.execute(new Runnable() {
						@Override public void run() {
							Bitmap bitma = mClipImageLayout.clip();
							path = Environment.getExternalStorageDirectory() + File.separator +IMAGE_FILE_NAME;
							saveBitmap(bitma, path);//如果不调用，成功后放回上一页面 就显示不出来。
							//String imeUrl = StringUtil.getStringUtilNew().uploadHead(MyApplication.getApp().getFWQString());
							String imeUrl = "http://123.207.110.98:8080";
							Map<String,Object> map = new HashMap<>();
							mFile = new File(path);
							map.put("file",mFile);
							map.put("userid",mId);
							map.put("token",mToken);
							getLogger().info("上传头像---FWQ"+imeUrl + Url.UploaDing_IMAGE+" mFile"+mFile+"mFileLength.."+mFile.length());
							GreenTreeNetworkUtil.getInstance().doPostFile(imeUrl + Url.UploaDing_IMAGE,map,new RequestDataCallback() {
								@Override
								public void onSuccess(String response) {
									try {
										JSONObject jsonObject = new JSONObject(response);
										mUploadDialog.dismiss();
										getLogger().info("上传头像---onSuccess()---String"+response);
										Log.e("jsonObject","             "+jsonObject.getInt("code"));
										if(jsonObject.getInt("code") == 1){
											Toast.makeText(ClipImageActivity.this,R.string.upload_yes,Toast.LENGTH_SHORT).show();
											Intent intent = new Intent();
											intent.putExtra(RESULT_PATH,path);
											setResult(RESULT_OK, intent);
											finish();
										}else if(jsonObject.getInt("code") == -2) {
											CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ClipImageActivity.this);
											crowdRetunDialog.show();
										}else {
											Toast.makeText(ClipImageActivity.this, R.string.uplod_no,Toast.LENGTH_SHORT).show();
										}

									} catch (JSONException e) {e.printStackTrace();}
								}

								@Override
								public void onFailure(Throwable error) {
									mUploadDialog.dismiss();
									StringUtil.getStringUtilNew().getExceptionCode(ClipImageActivity.this,error.toString());
								}
							});
						}
					});

					break;
				case R.id.iv_back:
					if(mUploadDialog !=null){
						mUploadDialog.dismiss();
					}
					finish();
					break;
			}
		}
	};

	/**
	 * 初始化
	 */
	private void init() {
		LinearLayout ivBack = (LinearLayout) findViewById(R.id.iv_back);
		TextView tvUse = (TextView)findViewById(R.id.tv_use);
		tvUse.setOnClickListener(l);
		ivBack.setOnClickListener(l);
		mClipImageLayout = (ClipImageLayout) findViewById(R.id.clipImageLayout);
		mPath = getIntent().getStringExtra(PASS_PATH);
		LogUtil.eE("",mPath);
	}

	private void saveBitmap(Bitmap bitmap, String path) {
		File f = new File(path);
		if (f.exists()) {
			f.delete();
		}

		FileOutputStream fOut = null;
		try {
			f.createNewFile();
			fOut = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (fOut != null)
					fOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
     * 创建图片
     */
    private Bitmap createBitmap(String path) {
        if (path == null) {
            return null;
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //不在内存中读取图片的宽高
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;

        opts.inSampleSize = width > 1080 ? width / 1080 : 1 ;//注意此处为了解决1080p手机拍摄图片过大所以做了一定压缩，否则bitmap会不显示

        opts.inJustDecodeBounds = false;// 这里一定要将其设置回false，因为之前我们将其设置成了true
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        opts.inDither = false;
        opts.inPurgeable = true;
        FileInputStream is = null;
        Bitmap bitmap = null;
        try {
            is = new FileInputStream(path);
            bitmap = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bitmap;
    }

	// 读取图像的旋转度
	private int readBitmapDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	// 旋转图片
	private Bitmap rotateBitmap(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, false);
		return resizedBitmap;
	}

	/**  上传图片 */
	/*public void uploadMethod(final RequestParams params,final String uploadHost,final String path){


		httpUtils.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {

			@Override public void onStart() {}

			@Override public void onLoading(long total, long current,boolean isUploading) {}

			@Override public void onSuccess(ResponseInfo<String> responseInfo) {

				try {
					JSONObject jsonObject = new JSONObject(responseInfo.result);
					mUploadDialog.dismiss();
					getLogger().info("上传头像---onSuccess()---String"+responseInfo.result);
					Log.e("jsonObject","             "+jsonObject.getInt("code"));
					if(jsonObject.getInt("code") == 1){
						Toast.makeText(ClipImageActivity.this,R.string.upload_yes,Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.putExtra(WeAccountAcivity.RESULT_PATH,path);
						setResult(RESULT_OK, intent);
						finish();
					}else if(jsonObject.getInt("code") == -2) {
						CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ClipImageActivity.this);
						crowdRetunDialog.show();
					}else {
						Toast.makeText(ClipImageActivity.this, R.string.uplod_no,Toast.LENGTH_SHORT).show();
					}

				} catch (JSONException e) {e.printStackTrace();}

			}

			@Override public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {
				mUploadDialog.dismiss();
				StringUtil.getStringUtilNew().getExceptionCode(ClipImageActivity.this, e.toString());
			}
		});
	}*/

	/**
	 * 系统返回键
	 */
	@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(mUploadDialog !=null){
				mUploadDialog.dismiss();
			}
			this.finish();
		}
		return true;
	}
}
